package cn.yunyichina.provider.pay.icbc.utils;

import java.io.FileInputStream;
import java.io.DataInputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.ArrayList;
import java.util.Calendar;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class TesterpTrans {

	public static void main(String[] args)
	{
		TesterpTrans theApp = new TesterpTrans();   
		theApp.run();			
	}	
	
	
	
	XMLParsor outParsor = null;
	String sTemplatePath = "./config/"; //模板xml路径
	String sTargetPath = "./config/testout.xml"; //生成的xml路径
	String sTesterName = "";
	String sTransCode = "";
	String sGroupCIS = "";
	String sID = "";
	String sPackageID = "";
	String sBankCode = "102";
	String sTranDate = "";
	String sTranTime = "";
	String sFSeqno = "";
	String sISeqno = "";
	private String sIp = null;
	private String sPort = null;

	private int retsignatureflg = 0;
	private int returnFlag = 0;
	private String sysout =""; //工行返回的信息
	String sContent = ""; //生成xml格式的字符串


	public void run() {

		
			sendNCMessage();
			if (returnFlag == 200) {
				
				try {
					
					//创建一个可以随机访问的对象,可以同时读写它,seek()方法直接移到文件的任意位置
					RandomAccessFile logFile =
						new RandomAccessFile(
							"./config/send.log",
							"rw");
					logFile.seek(logFile.length());

					Calendar rightNow = Calendar.getInstance(); //日历的基类		
					int month = rightNow.get(Calendar.MONTH) + 1;
					int date = rightNow.get(Calendar.DAY_OF_MONTH);
					int hour = rightNow.get(Calendar.HOUR_OF_DAY);
					int minute = rightNow.get(Calendar.MINUTE);
					int second = rightNow.get(Calendar.SECOND);
					logFile.writeBytes(
						"[Send success :  "
							+ month
							+ "."
							+ date
							+ "  "
							+ hour
							+ ":"
							+ minute
							+ ":"
							+ second
							+ "]"
							+ "\r\n");

					logFile.write(sContent.getBytes());

					logFile.writeBytes("\r\n\r\n");
					logFile.writeBytes("Receive from ICBC");
					logFile.writeBytes("\r\n\r\n");
					logFile.writeBytes(sysout);
					logFile.writeBytes("\r\n\r\n");
					logFile.close();

				
				} catch (IOException e) {
					mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, e);

				}
			} else {
				try {

					//创建一个可以随机访问的对象,可以同时读写它,seek()方法直接移到文件的任意位置
					RandomAccessFile logFile =
						new RandomAccessFile(
							"./config/send.log",
							"rw");
					//日志文件
					logFile.seek(logFile.length());

					Calendar rightNow = Calendar.getInstance(); //日历的基类		
					int month = rightNow.get(Calendar.MONTH) + 1;
					int date = rightNow.get(Calendar.DAY_OF_MONTH);
					int hour = rightNow.get(Calendar.HOUR_OF_DAY);
					int minute = rightNow.get(Calendar.MINUTE);
					int second = rightNow.get(Calendar.SECOND);
					logFile.writeBytes(
						"[Send again :  "
							+ month
							+ "."
							+ date
							+ "  "
							+ hour
							+ ":"
							+ minute
							+ ":"
							+ second
							+ "]"
							+ "\r\n");

					logFile.write(sContent.getBytes());

					logFile.writeBytes("\r\n\r\n");
					logFile.close();

				} catch (IOException e) {
					mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, e);

				}

				

			}

		
	}

	boolean sendNCMessage() {
		
	/*	
		Calendar rightNow = Calendar.getInstance(); //日历的基类		
		int year = rightNow.get(Calendar.YEAR);
		int month = rightNow.get(Calendar.MONTH) + 1;
		int date = rightNow.get(Calendar.DAY_OF_MONTH);
		int hour = rightNow.get(Calendar.HOUR_OF_DAY);
		int minute = rightNow.get(Calendar.MINUTE);
		int second = rightNow.get(Calendar.SECOND);

		String sendTime =
			String.valueOf(year)
				+ String.valueOf(month)
				+ String.valueOf(date)
				+ String.valueOf(hour)
				+ String.valueOf(minute)
				+ String.valueOf(second);
		
		System.out.println(sendTime); 
	 */
		

		StringFileParse sf = new StringFileParse("/conf/conf.ini");
		String NCIp = sf.getAttr("NCIp").trim();
		String NCPort = sf.getAttr("NCPort").trim(); //加密端口号
		String NCPort2 = sf.getAttr("NCPort2").trim(); //签名端口号

		String XMLDATA1 = sf.getAttr("XMLDATA1").trim(); 
		String XMLDATA2 = sf.getAttr("XMLDATA2").trim();  //交易代码
		String XMLDATA3 = sf.getAttr("XMLDATA3").trim();  
		String XMLDATA4 = sf.getAttr("XMLDATA4").trim();   //集团CIS
		String XMLDATA5 = sf.getAttr("XMLDATA5").trim();  
		String XMLDATA6 = sf.getAttr("XMLDATA6").trim();    //用户id
		String XMLDATA7 = sf.getAttr("XMLDATA7").trim();
		String XMLDATA8 = sf.getAttr("XMLDATA8").trim();
		String XMLDATA9 = sf.getAttr("XMLDATA9").trim();
		String XMLDATA10 = sf.getAttr("XMLDATA10").trim();  
		String XMLDATA11 = sf.getAttr("XMLDATA11").trim();
		String XMLDATA12 = sf.getAttr("XMLDATA12").trim();   //指令顺序号,每次提交都不同
		String XMLDATA13 = sf.getAttr("XMLDATA13").trim();
		String XMLDATA14 = sf.getAttr("XMLDATA14").trim();
		String XMLDATA15 = sf.getAttr("XMLDATA15").trim();

		//明文组包
		sContent =XMLDATA1+XMLDATA2+XMLDATA3+XMLDATA4+XMLDATA5+XMLDATA6+XMLDATA7+XMLDATA8+XMLDATA9+XMLDATA10+XMLDATA11+XMLDATA12+XMLDATA13+XMLDATA14+XMLDATA15;
		System.out.println("明文组包:"+sContent);
		//指令顺序号就当作是PackageID
			sPackageID =XMLDATA12;		    	
			sTransCode=XMLDATA2;
			sGroupCIS=XMLDATA4;
			sID=XMLDATA6;
			sPackageID=XMLDATA12;
		
		
		try {
				java.net.URL aURL =
					new java.net.URL("http://" + NCIp + ":" + NCPort2);
				java.net.HttpURLConnection urlConnection =
					(java.net.HttpURLConnection) aURL.openConnection();
                 

				urlConnection.setRequestMethod("POST");
				urlConnection.setDoInput(true);
				urlConnection.setDoOutput(true);
				urlConnection.setUseCaches(false);

				//urlConnection.setRequestProperty("User-Agent", "MSIE");

				urlConnection.setRequestProperty("Content-Length",String.valueOf(sContent.getBytes().length));
				urlConnection.setRequestProperty("Content-Type","INFOSEC_SIGN/1.0");
				
			 BufferedOutputStream out =new BufferedOutputStream(urlConnection.getOutputStream());
	
					
				out.write(sContent.getBytes());
				out.flush();
				out.close();
				//System.out.println("Connecting with the server...");
				urlConnection.connect();

				int responseCode = urlConnection.getResponseCode();
				if (responseCode != 200)
					return false;
				String resM = urlConnection.getResponseMessage();
				
				Thread.sleep(5000);
				BufferedInputStream bbb =
					new BufferedInputStream(urlConnection.getInputStream());
				byte[] ccc = new byte[urlConnection.getContentLength()];
				bbb.read(ccc);
				//System.out.println("签名端返回的数据：" + new String(ccc));
				System.out.println("接收签名端数据成功：" + new String(ccc));

				//System.out.println(resCode);
				//System.out.println("resM=" + resM);

				//		signpost.setRequestBody(sContent);
				int conTimeout = 30000;
				int timeout = 30000;

				String repContent = new String(ccc);
				repContent.replaceAll("\n","");
				
				urlConnection.disconnect();
				
				int beginSign = repContent.indexOf("<sign>") + 6;
				int endSign = repContent.indexOf("</sign>");

				String repSignContent =
					repContent.substring(beginSign, endSign);


				String urlStr1 = "http://" + NCIp + ":" + NCPort+"/servlet/ICBCCMPAPIReqServlet?userID="+				
				                  sID+"&PackageID="+sPackageID+"&SendTime="+XMLDATA14;
				
//				推广版提交格式“/servlet/ICBCCMPAPIReqServlet?userID=epaylinkshoukuan.y.3602&PackageID=3710&SendTime=20100610150307515”
//				普通版提交格式“/servlet/com.icbc.inbs.yhzq.NCAPIReqServlet?userID=GDTEL11.d.3602&PackageID=201001251725421&SendTime=20100125235543”
				
				
				HttpClient myclient = new HttpClient(); //构建http客户端	
				PostMethod mypost = new PostMethod(urlStr1); //加密端口

				mypost.addParameter("Version", "0.0.0.1");
				mypost.addParameter("TransCode", sTransCode);
				mypost.addParameter("BankCode", sBankCode);
				mypost.addParameter("GroupCIS", sGroupCIS);
				mypost.addParameter("ID", sID);
				mypost.addParameter("PackageID", sPackageID);
				mypost.addParameter("Cert", "");

				mypost.addParameter("reqData", repSignContent);
				
				
				//本例repSignContent是经过发签名端口加密后的数据，如果是查询交易repSignContent为包明文,不需要发NC449端口签名。
				//System.out.println("发送到加密端的数据：" + repSignContent);

				System.out.println("开始发送到加密端...");
				returnFlag = myclient.executeMethod(mypost); //获得http返回码
				System.out.println("已返回数据...");
				
				try {
					String postResult = mypost.getResponseBodyAsString();
					
					System.out.println("工行返回数据如下:" + new String(postResult.getBytes("ISO8859-1"),"gb2312"));
					
					postResult = postResult.substring(8);
					byte[] decodeResult = getFromBASE64(postResult);
						
					 sysout = new String(decodeResult);
                    System.out.println("base64解码如下:" +sysout);
                       


				} catch (Exception e) {
					e.printStackTrace();
				}
				mypost.releaseConnection(); //释放http连接

			
		} catch (IOException e) {
			
			e.printStackTrace();
			
			e.printStackTrace(System.out);
			
			mypage.FcfeMain.wR(
				mypage.FcfeMain.SIM_APP_ERP,
				"\n\n\n\t\t\t***********************\n\n\n\t\t              指令发送失败，请检查NetSafe是否正常！\n\n\n\t\t\t***********************\n");
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			
			e.printStackTrace(System.out);
			
			System.err.println("error:" + e.getMessage());
		}

		return true;
	}
	/**
	 * 
	 * @param 
	 * @return
	 */


	public static byte[] getFromBASE64(String s) {
		if (s == null)
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			return decoder.decodeBuffer(s);
		} catch (Exception e) {
			return null;
		}
	}
	
	public static String getrevFromBASE64(String s) {
		if (s == null)
			return null;
		BASE64Encoder encoder = new BASE64Encoder();
		try {
			return encoder.encode(s.getBytes());
		} catch (Exception e) {
			return null;
		}
	}

}
